import { BaseToolProvider } from "./base";
import { z } from "zod";
import * as vscode from 'vscode';
import { ToolCall } from "./types";

export class TerminalToolProvider extends BaseToolProvider {
	constructor() {
		super();
		this.addTool({
			name: 'execute_command',
			description: "在VSCode终端中执行命令",
			parameters: z.object({
				command: z.string({ description: "待执行命令", required_error: '没有待执行的命令' })
			})
		}, this.executeCommand);
	}

	async executeCommand(call: ToolCall): Promise<any> {
		const terminal = vscode.window.createTerminal('Ai Code Agent Terminal Tool');
		terminal.show();

		await this.waitForShellIntegration(terminal, 5000);
		const parameter = JSON.parse(call.arguments);
		const execution = terminal.shellIntegration?.executeCommand(parameter.command);
		if(execution) {
			let terminalResult = '';
			const terminalStream = execution.read();
			for await (const chunk of terminalStream) {
				terminalResult += chunk;
			}
			return terminalResult;
		}
		return '';
	}

	private async waitForShellIntegration(
		terminal: vscode.Terminal,
		timeout: number
	): Promise<void> {
		let resolve: () => void;
		let reject: (e: Error) => void;
		const p = new Promise<void>((_resolve, _reject) => {
			resolve = _resolve;
			reject = _reject;
		});
	
		const timer = setTimeout(() => reject(new Error('没有发现这个你在运行的终端: shell integration 没有启用')), timeout);
	
		const listener = vscode.window.onDidChangeTerminalShellIntegration((e) => {
			if (e.terminal === terminal) {
				clearTimeout(timer);
				listener.dispose();
				resolve();
			}
		});
	
		await p;
	}
}